package com.java1234.jxc.controller.admin;

import com.java1234.jxc.beans.Supplier;
import com.java1234.jxc.core.page.Pagination;
import com.java1234.jxc.service.SupplierService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.rmi.MarshalledObject;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/supplier")
public class SupplierController {

    private final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    SupplierService supplierService;

    @Autowired
    Dao dao;


    @RequestMapping("/comboList")
    public Object comboList (String name){
        List<Supplier> suppliers = supplierService.query(Cnd.where("name", "like", "%" + name + "%"));
        return suppliers;
    }


    @RequestMapping("/list")
    public Object  list( @RequestParam(value = "page",required = false,defaultValue = "1")Integer page,
                         @RequestParam(value = "rows",required = false,defaultValue = "10")Integer rows){
        NutMap result = NutMap.NEW();
        Pagination pagination = supplierService.listPage(page, rows, Cnd.where(null));
        List<?> list = pagination.getList();
        int total = pagination.getTotalCount();

        result.put("rows",list);
        result.put("total",total);
        return result;
    }


    @RequestMapping("/save")
    public Object save(Supplier supplier){
        NutMap result = NutMap.NEW();

        if (supplier.getId()==null){
            supplierService.save(supplier);

        }else{
            supplierService.updateIgnoreNull(supplier);
        }
        result.put("success",true);
        return result;
    }




    @RequestMapping("/delete")
    public Object delete(String ids){
        NutMap result = NutMap.NEW();
        try{


            String[] idStrs = ids.split(",");

            Arrays.stream(idStrs).forEach(idStr->{
                int id = Integer.parseInt(idStr);
                supplierService.delete(id);

            });
            result.put("success",true);

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            result.put("success",false);
        }
        return result;
    }




}
